package com.DeviceTest;

import android.os.Message;
import android.os.SystemService;
import android.util.Log;
import android.view.View;

import com.DeviceTest.helper.PCIEInfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PCIETestActivity extends UsbHostTestActivity {
    private static final String TAG = "PCIETestActivity";
    private static final int MSG_CHECK_PCIE_INFO_FILE = 11;

    private boolean mStop;
    private String mPCIEInfoPath;
    private String mStrStorageResult;

    @Override
    protected void preData() {
        mStorageType = STORAGE_TYPE.PCIE;
    }

    @Override
    protected void dealMessage(Message msg) {
        if (mStop) {
            return;
        }
        switch (msg.what) {
            case MSG_CHECK_PCIE_INFO_FILE:
                testPcieInfo();
                break;
            default:
                break;
        }
    }

    private void testPcieInfo() {
        String staFlag = "LnkSta:";
        List<String> list = readPcieInfoTxt(mPCIEInfoPath, new String[]{staFlag}, "\t");
        if (list.size() < 1 /*|| list.size() % 2 == 1*/) {
            appendResultText("pcieInfo file txt err");
            mHandler.sendEmptyMessageDelayed(R_FAIL, BACK_TIME);
            return;
        }
        StringBuilder sb = new StringBuilder();
        for (String temp : list) {
            sb.append(temp + "\n");
        }
        Log.v(TAG, sb.toString());
        appendResultText(sb.toString());

        List<PCIEInfo> lnkModelList = fillPcieInfoTxt(list, staFlag);
        if (lnkModelList.size() < 1/* || lnkModelList.size() % 2 == 1*/) {
            sb.append("\npcieInfo lnk txt err");
            appendResultText(sb.toString());
            mHandler.sendEmptyMessageDelayed(R_FAIL, BACK_TIME);
            return;
        }

        sb = new StringBuilder();
        for (PCIEInfo lnk : lnkModelList) {
            sb.append("\n");
            sb.append(lnk.toString());
        }
        appendResultText(sb.toString());
        findViewById(R.id.btn_Pass).setVisibility(View.VISIBLE);
        findViewById(R.id.btn_Pass).setClickable(true);
        findViewById(R.id.btn_Fail).setVisibility(View.VISIBLE);
        findViewById(R.id.btn_Fail).setClickable(true);
    }

    private List<String> readPcieInfoTxt(String path, String[] containWords, String replace) {
        List<String> list = new ArrayList<String>();
        BufferedReader br = null;
        FileReader fr = null;
        try {
            File file = new File(path);
            if (!file.exists()) {
                Log.e(TAG, path + " not exists");
                return list;
            }
            fr = new FileReader(file);
            br = new BufferedReader(fr);
            String lineText;
            while ((lineText = br.readLine()) != null) {
                lineText = lineText.replaceAll("\t", "");
                for (String containWord : containWords) {
                    if (lineText.contains(containWord)) {
                        list.add(lineText);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (null != fr) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    private List<PCIEInfo> fillPcieInfoTxt(List<String> vvInfoList, String staFlag) {
        List<PCIEInfo> lnks = new ArrayList<PCIEInfo>();
        for (String vvInfo : vvInfoList) {
            if (vvInfo.startsWith(staFlag)) {
                PCIEInfo tempLnk = new PCIEInfo();
                String[] temps = vvInfo.replace(staFlag, "").split(", ");
                for (String temp : temps) {
                    if (temp.startsWith("Speed ")) {
                        tempLnk.setStaSpeed(temp.replace("Speed ", ""));
                    } else if (temp.startsWith("Width ")) {
                        tempLnk.setStaWidth(temp.replace("Width ", ""));
                    }
                }
                lnks.add(tempLnk);
            }
        }
        return lnks;
    }

    private void appendResultText(String ss) {
        mResult.setText(mStrStorageResult + "\n\n" + ss);
    }

    @Override
    protected void childTest() {
        Log.v(TAG, "test PCIE info");
        if (null != mResult.getText() && null != mResult.getText().toString()) {
            mStrStorageResult = mResult.getText().toString();
        }
        appendResultText("waiting PCIE info test...");
        mPCIEInfoPath = "/mnt/sdcard/pcieInfo.tmp";
        File file = new File(mPCIEInfoPath);
        if (null != file && file.exists()) {
            file.delete();
        }
        try {
            SystemService.start("read_pcie_info");
            mHandler.sendEmptyMessageDelayed(MSG_CHECK_PCIE_INFO_FILE, 2000);
        } catch (Exception e) {
            appendResultText("err " + e.getMessage());
            mHandler.sendEmptyMessageDelayed(R_FAIL, BACK_TIME);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mStop = true;
        mHandler.removeMessages(MSG_CHECK_PCIE_INFO_FILE);
    }
}